<template>
	<view class="wrapperBg">
		<view class="item-top">
			<uni-search-bar :focusStus="false" :isShow="true" :radius="5" :value="BuilStatus ? BuilDataStr : val"
				:disabled="BuilStatus" clearButton="always" placeholder="请选择/搜索需要报障的电梯" @focus="focusInput"
				@blurs="searchInput" @searchHand="searchHand">
			</uni-search-bar>
			<!-- <uni-search-bar v-else :isShow="true" :radius="5" :value="val"  clearButton="always"  placeholder="按项目关键词搜索" @blurs="searchInput">
			</uni-search-bar> -->
		</view>
		<block>
			<view class="item-conten">
				<scroll-view @scrolltolower="scrolltolower" :style="{ height: pageHight - 130 + 'px' }" class="tab"
					:scroll-y="true" :scroll-into-view="toView" scroll-with-animation>
					<block v-if="!focusShow">
						<view class="conten_tit">我的项目({{ totalCount }})</view>
						<view class="conten_cont" :data-current="i" @click.native="searchName($event, item, i, 'garden')"
							v-for="(item, i) in gardenList" :key="i">
							<view :class="item.elevatorShow ? 'cont_C' : 'cont_L'">
								<view>{{ item.buildingName }}</view>
								<view>{{ item.address }}</view>
							</view>
						</view>
						<uni-load-more v-if="isStateMore" :status="state" :contentText="contentText"></uni-load-more>
					</block>
					<block v-else>
						<view class="conten_tit" v-if="listResult.length > 0 && historyShow">
							搜索到<text>{{ listResult.length }}</text>个项目</view>
						<view class="conten_tit" v-else>搜索历史</view>
						<view class="nodata" v-if="listResult.length <= 0">暂无搜索历史</view>
						<view :id="'gd' + (i + 1)" class="conten_cont" :data-current="i"
							@click.native="searchName($event, item, i)" v-for="(item, i) in listResult" :key="i">
							<view :class="item.elevatorShow ? 'cont_C' : 'cont_L'">
								<view>{{ item.buildingName || item.name }}</view>
								<view>{{ item.address }}</view>
							</view>
						</view>
					</block>

				</scroll-view>
			</view>

		</block>
		<block v-if="radioShow">
			<view class="C_Elevator" :style="{ height: pageHight - 130 + 'px' }">
				<view class="item_title">我的电梯</view>
				<uni-load-more v-if="!moreState" :status="asyncState" :contentText="contentText"></uni-load-more>
				<view class="item_titleEle" @click.native="handElevator(item)" v-for="(item, i) in listRadio" :key="i">
					<view v-if="!isMultiSelect" :class="item.pstatus ? 'actives' : ''">{{ item.elevatorAddress || '--' }}</view>
					<view v-else class="check-item">
						<view class="check-item-icon" :class="item.pstatus ? 'checked' : ''"></view>
						<view class="check-item-content">{{ item.elevatorAddress || '--' }}</view>
					</view>
				</view>
				<!-- <block v-if="!focusShow">
				<view class="item_title">其他全部电梯({{listOtherAll.length}})</view>
				<view class="item_titleEle" @click.native="handElevator(item,'other')" v-for="(item,i) in listOtherAll" :key="i">
					<view :class="item.status?'actives':''">{{item.elevatorName||'--'}}</view>
				</view>	
				</block> -->
			</view>
		</block>
		<view v-if="btnShow" class="item_botm" @click="nextBarrPage">
			<view :class="btnState || (isMultiSelect && selectedElevators.length > 0) ? 'botm' : 'botms'">
				{{ isEdit ? '确认' : '下一步' }}
			</view>
		</view>
		<uni-popup-box ref="myPopupBox"></uni-popup-box>
	</view>
</template>

<script>
import {
	getElevatorGroup,
	getElevatorListGroup,
	myMaintainBuilding,
	myMaintainBuildingChilds

} from '@/apis/barrierSearch.js';
import { hanleToken } from '@/utils/utils.js';
import { mapState } from 'vuex';
export default {
	name: 'searchBg',
	data() {
		return {
			showPopup:false,
			pageHight: uni.getSystemInfoSync().windowHeight,
			val: '',
			// 电梯列表
			listRadio: [],
			// 小区列表
			listResult: [],
			// 小区和电梯列表状态
			radioShow: false,
			// 搜索历史状态
			historyShow: false,
			// 下一步按钮状态
			btnShow: true,
			// 下一步按钮显示隐藏
			btnState: false,
			// input框状态
			BuilStatus: false,
			// 电梯数据
			objData: {},
			// 小区数据
			BuilData: {},
			BuilDataStr: '',
			// 电梯样式状态
			elevatorShow: false,
			contentText: {
				contentdown: '加载更多',
				contentrefresh: '加载中...',
				contentnomore: '暂无数据~'
			},
			asyncState: 'loading',
			// 更多数据状态
			moreState: false,
			// 其他电梯更多数据状态
			otherState: false,
			// 维保过的数组
			gardenList: [],
			// 维保过 去重后数组
			gardenArrRep: [],
			// 区分维保过电梯 状态
			gardenState: false,
			toView: '',
			// 光标聚焦状态
			focusShow: false,
			// 其他全部电梯列表
			listOtherAll: [],
			pages: {
				current: 1,
				size: 10,
			},
			totalPages: 0,
			totalCount: 0,
			// contentText: {
			// 	contentdown: '上拉显示更多',
			// 	contentrefresh: '正在加载...',
			// 	contentnomore: '没有更多了',
			// },
			state: '',
			// 只有一页数据隐藏更多显示
			isStateMore: false,
			// 判断是跳转去报障页(0)还是去配件申请页面(1)
			type: '',
			// 判断是否为修改报障信息
			isEdit: false, 
			// 修改报障信息 回显
			elevatorData: {}, 
			rescueNoticeId:'',
			isMultiSelect: false,
			selectedElevators: [],
		};
	},
	computed: {
		...mapState('user', ['userinfo'])
	},
	onLoad(e) { 
		if (e.type) {
			this.type = e.type;
		}
		if (e.isEdit) {
			this.isEdit = e.isEdit;
			this.elevatorData = JSON.parse(e.data);
		}
		if (e.rescueNoticeId) {
			// 报警id
			this.rescueNoticeId = e.rescueNoticeId;
		}
		if (e.multiSelect) {
			this.isMultiSelect = true;
		}
	},

	mounted() {
		if (hanleToken('get', 'historyList').length > 0) {
			this.historyShow = false;
			this.listResult = hanleToken('get', 'historyList');
		}
		let groupLeader = this.userinfo.groupLeader || ''; 
		this.handMyElevator(groupLeader);
	},

	methods: {
		// 小区列表 报障页面第4次修改2022-05-20
		handBuilding(str) {
			let { size, current } = this.pages;
			myMaintainBuilding({
				size,
				current,
				buildingName: str
			}).then(res => {
				if (res.code === 200) {
					let data = res.data.records || [];
					if (data.length > 0) {
						this.historyShow = true;
						this.listResult = data;
						this.pageHight = uni.getSystemInfoSync().windowHeight + 100;
					}
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},
		// 电梯列表
		handlistElevator(objData, type) {
			this.moreState = false;
			this.asyncState = 'loading';
			let result;
			let objDataId = objData.buildingId || objData.id;
			if (this.userinfo.groupLeader === 1) {
				result = getElevatorListGroup({ buildingId: objDataId, size: 200, current: 1 });
			} else {
				// 走这里
				result = myMaintainBuildingChilds({ buildingId: objDataId, size: 200, current: 1 });
			}
			result.then(res => {
				if (res.code === 200) {
					let data;
					if (this.userinfo.groupLeader === 1) {
						data = res.data || [];
					} else {
						data = res.data.records || [];
					}
					this.listRadio = data;
					if (type == 'other') {
						// let myItemArr = this.listRadio//小区维保过的电梯
						if (data.length > 0) {
							this.moreState = true;
						} else {
							this.moreState = false;
							this.asyncState = 'noMore';
						}
					} else {
						// this.listRadio = data
						// if(data.length > 0){
						// 	this.moreState = true
						// 	for(let i = 0; i < res.data.length; i++){
						// 		this.listRadio[i].elevatorAddress = this.listRadio[i].elevatorName
						// 		this.listRadio[i].status = false
						// 	}
						// }else{
						// 	this.moreState = false
						// 	this.asyncState = "noMore"
						// }
					}
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		},

		// 维保过的小区
		handMyElevator(leader, type) {
			let promise;
			this.state = 'loading';
			if (leader === 1) {
				this.pages.groupId = this.userinfo.maintainGroupId;
				promise = getElevatorGroup(this.pages);
			} else {
				// 走这里
				this.pages.user_id = this.userinfo.user_id;
				promise = myMaintainBuilding(this.pages);
			}

			promise.then(res => {
				if (res.code === 200) {
					let recordList = res.data.records || [];
					if (recordList.length > 0) {
						this.totalCount = res.data.total;
						this.totalPages = res.data.pages;
						let orginList = this.gardenList;
						this.gardenList = orginList.concat(recordList);
					} else {
						this.state = 'noMore';
					}

					if (res.data.pages === 1) {
						this.isStateMore = false;
					} else {
						this.isStateMore = true;
					}

					if (type === 'act') {
						this.gardenList = recordList;
					}
				}
			});
		},
		// 下拉加载
		scrolltolower() {
			if (this.pages.current <= this.totalPages) {
				this.pages.current += 1;
				this.handMyElevator(this.userinfo.groupLeader);
			} else {
				this.state = 'noMore';
			}
		},
		// 搜索清除点击
		searchHand() {
			if (this.isMultiSelect) {
				this.selectedElevators = [];
			}
			this.pageHight = uni.getSystemInfoSync().windowHeight;
			let listResultArr = hanleToken('get', 'historyList') || [];
			let gardenArrRepA = this.gardenList;
			// 清除搜索历史选中样式
			for (let i = 0; i < listResultArr.length; i++) {
				listResultArr[i].elevatorShow = false;
			}
			// 清除维保过选中样式
			for (let i = 0; i < gardenArrRepA.length; i++) {
				gardenArrRepA[i].elevatorShow = false;
			}
			this.listResult = listResultArr;
			this.focusShow = false;
			this.btnShow = true;
			// this.handBuilding(val)
		},
		// 搜索框光标聚焦
		focusInput() {
			if (this.listResult.length <= 0) {
				this.pageHight = uni.getSystemInfoSync().windowHeight - 400;
			} else {
				this.pageHight = 0;
			}
			this.btnShow = false;
			this.focusShow = true;
		},
		// 搜索框
		searchInput(val) {
			this.val = val;
			this.pages.current = 1;
			if (this.isMultiSelect) {
				this.selectedElevators = [];
			}
			if (!val) {
				// 区分清除时 初始文本框
				if (this.BuilStatus) {
					this.BuilStatus = false;
					this.btnState = false;
				}
				setTimeout(() => {
					// this.listResult = hanleToken("get","historyList") || []
					// 历史数据状态
					this.historyShow = false; 
				}, 100);
			} else {
				// 初始文本框
				this.BuilStatus = false;
				this.handBuilding(val);
			}
			// 历史数据状态
			this.radioShow = false; 
		},
		// 搜索结果点击
		searchName(e, obj, index, type) {
			let arr = [];
			let listResultArr = this.listResult;
			let gardenArrRepA = this.gardenList;
			let hisList = hanleToken('get', 'historyList') || [];
			if (this.isMultiSelect) {
				this.selectedElevators = [];
			}
			// let indexs = e.currentTarget.dataset.current
			// if(!type){
			// 	this.$nextTick(() => {
			// 		this.toView = "gd"+indexs
			// 	});
			// }
			// 区分维保过的不缓存
			if (Object.keys(obj).length > 0 && !type) { 
				if (hisList.length > 0) {
					var objs = {};
					hisList.push(obj);
					hisList = hisList.reduce(function (item, next) {
						objs[next.buildingId] ? '' : objs[next.buildingId] = true && item.push(next);
						return item;
					}, []);
					// 限制搜索历史数量
					if (hisList.length >= 5) {
						hisList = hisList.splice(0, 5);
					}
					arr = hisList;
				} else {
					arr.push(obj);
				}
				hanleToken('set', 'historyList', arr);
			}
			if (type == 'garden') {
				for (let i = 0; i < gardenArrRepA.length; i++) {
					if (gardenArrRepA[i].buildingId === obj.buildingId) {
						gardenArrRepA[i].elevatorShow = true;
					} else {
						gardenArrRepA[i].elevatorShow = false;
					}
				}
				// this.listRadio = this.gardenList[index].child
				// this.listRadio.map(item=>item.status = false)//清除选中电梯样式
				this.handlistElevator(obj, 'other');
			} else {
				for (let i = 0; i < listResultArr.length; i++) {
					if (listResultArr[i].buildingId === obj.buildingId) {
						listResultArr[i].elevatorShow = true;
					} else {
						listResultArr[i].elevatorShow = false;
					}
				}
				this.handlistElevator(obj, 'other');
			}
			this.BuilData = obj;
			this.BuilDataStr = obj.name || obj.buildingName;
			this.BuilStatus = true;
			this.radioShow = true;
			this.btnState = false;
		},
		// 选择电梯
		handElevator(obj = {}, type) {
			console.log(obj, type, 'handElevator');
			this.pageHight = uni.getSystemInfoSync().windowHeight;
			var listArr = this.listRadio;
			var listOtherAll = this.listOtherAll;
			// 区分维保过的为电梯id
			let resultID = obj.elevatorId || obj.id;
			// 区分维保过的为电梯id
			let resID = obj.elevatorId ? 'elevatorId' : 'id'; 
			
			if (this.isMultiSelect) {
				// 多选模式
				const index = this.selectedElevators.findIndex(item => item[resID] === resultID);
				if (index > -1) {
					this.selectedElevators.splice(index, 1);
					obj.pstatus = false;
				} else {
					this.selectedElevators.push(obj);
					obj.pstatus = true;
				}
				// this.btnState = true;
				this.btnShow = true;
				this.$forceUpdate();
				return;
			}

			if (type === 'other') {
				for (let i = 0; i < listOtherAll.length; i++) {
					if (listOtherAll[i][resID] === resultID) {
						this.btnState = true;
						this.btnShow = true;
						listOtherAll[i].pstatus = true;
					} else {
						listOtherAll[i].pstatus = false;
					}
				}
				for (let i = 0; i < listArr.length; i++) {
					// 清除电梯选择
					listArr[i].pstatus = false;
				}
			} else {
				for (let i = 0; i < listArr.length; i++) {
					if (listArr[i][resID] === resultID) {
						this.btnState = true;
						this.btnShow = true;
						listArr[i].pstatus = true;
					} else {
						listArr[i].pstatus = false;
					}
				}
				// for(let i = 0; i < listOtherAll.length; i++){//清除其他选择
				// 	listOtherAll[i].status = false
				// }
			}
			this.objData = obj;
			this.$forceUpdate();
		},
		// 报障页面
		nextBarrPage() {
			if (!this.btnState && !this.isMultiSelect) {
				return;
			}

			if (this.isMultiSelect && this.selectedElevators.length === 0) {
				return;
			}

			if (this.isMultiSelect) {
				// 处理多选电梯的逻辑
				const elevators = this.selectedElevators.map(elevator => ({
					elevatorId: elevator.elevatorId || elevator.id,
					elevatorName: this.BuilData.buildingName || this.BuilData.name,
					elevatorAddress: elevator.elevatorAddress
				}));
				uni.setStorageSync('elevatorData', elevators);
				if (this.isEdit) {
					// 回显多选
					this.elevatorData.elevators = elevators;
					uni.navigateBack();
				} else if (this.type == 0) {
					// 跳转到报障页面，传递多选
					uni.setStorageSync('elevatorData', '');
					uni.navigateTo({
						url: '/pageModules/barrierSearch/barrierPage'
					});
				} else {
					// 跳转到配件页面，传递多选
					uni.navigateTo({
						url: '/pageModules/parts/applyParts?multiElevators=true&independent=true'
					});
				}
				return;
			}

			// 原有的单选逻辑
			if (Object.keys(this.objData).length > 0) {
				this.objData.id = this.objData.elevatorId || this.objData.id;
				this.BuilData.elevatorName = this.BuilData.buildingName || this.BuilData.name;
				const params = {
					elevatorId: this.objData.id,
					elevatorName: this.BuilData.elevatorName,
					elevatorAddress: this.objData.elevatorAddress
				};
				if (this.isEdit) {
					this.elevatorData.elevatorId = params.elevatorId;
					this.elevatorData.buildingName = this.objData.buildingName;
					this.elevatorData.elevatorAddress = params.elevatorAddress;
					uni.setStorageSync('elevatorData', this.elevatorData);
					uni.navigateBack();
				} else if (this.type == 0) {
					uni.setStorageSync('elevatorData', '');
					uni.navigateTo({
						url: '/pageModules/barrierSearch/barrierPage?params=' + JSON.stringify(params) + '&rescueNoticeId=' + this.rescueNoticeId
					});
				} else {
					uni.navigateTo({
						url: `/pageModules/parts/applyParts?id=${this.objData.id}&&independent=true`
					});
				}
			}
		}
	}
};
</script>

<style lang="scss">
page {
	background: #F3F6F8;
}

%widthMargin {
	width: 720rpx;
	margin: 0 auto;
}

;

.wrapperBg {
	height: calc(100vh - 0rpx);
	overflow-y: auto;
	overflow-x: hidden;
	position: relative;

	.item-top {
		background-color: #FFFFFF;
		height: 116rpx;
		line-height: 116rpx;
	}

	.item-conten {
		margin-top: 20rpx;
		background-color: #FFFFFF;
		position: relative;

		.conten_tit {
			font-size: 24rpx;
			font-weight: 400;
			padding: 20rpx 40rpx;
			color: #999999;

			text {
				color: #e02020;
				font-size: 24rpx;
			}
		}

		.conten_cont:last-child {
			border-bottom: none;
		}

		.nodata {
			width: 680rpx;
			margin: 0 auto;
			margin-top: 50rpx;
			text-align: center;
			font-size: 28rpx;
			color: #999999;
			font-weight: 400;
		}

		.conten_cont {
			display: flex;
			flex-direction: row;
			align-items: center;
			// height: 137rpx;
			border-bottom: 2rpx solid #eeeeee;

			.cont_L {
				flex: 1;
				padding: 40rpx;

				view:nth-child(1) {
					font-size: 28rpx;
					font-weight: 500;
					color: #333333;
					width: 370rpx;
				}

				view:nth-child(2) {
					font-size: 24rpx;
					font-weight: 400;
					color: #999999;
					width: 370rpx;
				}
			}

			.cont_C {
				flex: 1;
				background-color: #f8f8f8;
				padding: 40rpx;

				view:nth-child(1) {
					font-size: 28rpx;
					font-weight: 600;
					color: #0091ff;
					width: 370rpx;
				}

				view:nth-child(2) {
					font-size: 24rpx;
					font-weight: 400;
					color: #999999;
					width: 370rpx;
				}
			}

			.cont_R {
				text:nth-child(1) {
					display: block;
					width: 16rpx;
					height: 16rpx;
					border-bottom: 1rpx #999999 solid;
					border-right: 1rpx #999999 solid;
					transform: rotate(-45deg);
				}
			}
		}
	}

	.item-radio {
		margin-top: 20rpx;
		background-color: #FFFFFF;

		.radio_tit {
			background-color: #F3F6F8;
			height: 50rpx;
			padding-left: 20rpx;
			font-size: 24rpx;
			font-weight: 400;
			color: #999999;
		}

		.radioLR {
			display: flex;
			flex-direction: row;
			height: 103rpx;
			line-height: 103rpx;

			.radio_L {
				padding-left: 20rpx;
				flex: 0 0 70rpx;
				text-align: center;
				font-size: 28rpx;
				font-weight: 400;
				color: #999999;
			}

			.radio_R {
				flex: 1;
				display: flex;
				flex-direction: row;
				border-bottom: 2rpx #eeeeee solid;

				view:nth-child(1) {
					flex: 1;
				}

				view:nth-child(2) {
					flex: 0 0 80rpx;
				}
			}
		}

		.radioLR:last-child {
			.radio_R:last-child {
				border-bottom: none;
			}
		}
	}

	.item_botm {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 300;
		background-color: #FFFFFF;
		padding: 0 20rpx 0rpx 20rpx;
		height: 98rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		border-top: 1rpx #eee solid;

		/* #ifdef H5 */
		padding-bottom: constant(safe-area-inset-bottom);  
    	padding-bottom: env(safe-area-inset-bottom);  
    	/* #endif */

		.botm {
			@extend %widthMargin;
			height: 70rpx;
			background: #0091ff;
			border-radius: 8rpx;
			line-height: 70rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #ffffff;
		}

		.botms {
			@extend %widthMargin;
			height: 70rpx;
			background: #efefef;
			border-radius: 8rpx;
			line-height: 70rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #cccccc;
		}
	}

	.C_Elevator {
		overflow-y: auto;
		width: 330rpx;
		background-color: #f8f8f8;
		position: absolute;
		z-index: 300;
		top: 136rpx;
		right: 0;
		bottom: 0;

		.item_title {
			margin: 20rpx 0 40rpx 20rpx;
			font-size: 24rpx;
			font-weight: 500;
			color: #999999;
		}

		.item_titleEle {
			margin: 20rpx 20rpx 40rpx 20rpx;
			font-size: 28rpx;
			font-weight: 500;
			color: #333333;
			width: 290rpx;

			.actives {
				font-size: 28rpx;
				color: #0091ff;
				font-weight: 600;
			}

			.check-item {
				display: flex;
				align-items: center;
				padding: 8rpx 0;

				&-icon {
					min-width: 32rpx;
					width: 32rpx;
					height: 32rpx;
					border-radius: 50%;
					background-color: transparent;
					border: 2rpx solid #cccccc;
					margin-right: 16rpx;
				}

				.checked {
					border: 1px solid transparent;
					background-image: url("https://erised-fresh.oss-cn-shenzhen.aliyuncs.com/%E4%B8%8B%E8%BD%BD.png");
					background-size: 32rpx 32rpx;
					background-repeat: no-repeat;
				}

				&-content {
					flex: 1;
				}
			}
		}

	}
}
</style>
